use crate::tools::common;
use log::{error, info};
use rusqlite::{Connection, Result};

pub fn connect() -> Result<Connection> {
    match common::APP_CONFIG.lock().unwrap().get("app_local_data_dir") {
        Some(dir) => {
            let dir = format!(r"{}\dev_app_db.db", dir);
            info!("db-dir:{}", &dir);
            Connection::open(dir)
        }
        None => Err(rusqlite::Error::InvalidParameterName(
            "初始化失败!app_local_data_dir无效!".to_string(),
        )),
    }
}
pub fn init_db() -> Result<()> {
    let bind = common::DB_CONNECT.lock().unwrap();
    let conn = bind.as_ref().unwrap();

    //let conn = connect()?;
    conn.execute(
        r"
    create table if not exists tools_urls_class(
        c_id text primary key,
        c_name text,
        create_date text,
        update_date text,
        c_state text
    )
    ",
        [],
    )?;

    conn.execute(
        r"
      create table if not exists tools_urls(
        address_id text primary key,
        address_title text,
        address_url text,
        create_date text,
        update_date text,
        address_state text,
        c_id text
      )
    ",
        [],
    )?;

    conn.execute(
        r"
      create table if not exists tools_pass_class(
        c_id text primary key,
        c_name text,
        create_date text,
        update_date text,
        c_state text
      )
    ",
        [],
    )?;

    conn.execute(
        r"
      create table if not exists tools_pass(
        pass_id text primary key,
        pass_account text,
        pass_password text,
        pass_notes text,
        c_id text,
        create_date text,
        update_date text,
        pass_state text
      )
    ",
        [],
    )?;

    conn.execute(
        r"
      create table if not  exists tools_setting(
        s_id text primary key,
        s_title text,
        s_type text,
        s_value text,
        create_date text,
        update_date text
      )
    ",
        [],
    )?;

    conn.execute(
        r"
      create table if not  exists tools_todo(
        t_id text primary key,
        t_title text,
        t_state text,
        end_date text,
        remind_time text,
        repeat_rule text,
        rule_detail text,
        create_date text,
        update_date text,
        priority_level text,
        first_end_date text
      )
    ",
        [],
    )?;

    Ok(())
}
